package com.lyr.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/8/19 下午2:47
 */
@Repository
public class UserRepository {
    private final JdbcTemplate jdbcTemplate;
    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    // 查询用户表的记录总数
    public int countUsers() {
        return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM users", Integer.class);
    }

    public void createTableIfNotExists() {
        // 检查表是否存在
        try {
            jdbcTemplate.queryForObject("SELECT 1 FROM users FETCH FIRST ROW ONLY", Integer.class);
        } catch (Exception e) {
            // 表不存在，创建表
            jdbcTemplate.execute("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255))");
        }
    }
}

